package com.sefer.dragonfly.client.core.thread.scaner;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Map;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;

import com.sefer.dragonfly.client.constants.CachePolicyEnum;
import com.sefer.dragonfly.client.core.cache.CmCache;
import com.sefer.dragonfly.client.core.cache.CmCacheMuster;
import com.sefer.dragonfly.client.core.cache.CmCachePolicy;
import com.sefer.dragonfly.client.core.domain.MonitorData;
import com.sefer.dragonfly.client.core.domain.mbean.annotation.CMbean;
import com.sefer.dragonfly.client.tools.CmCacheTools;

/**
 * 扫描内存,清楚过期数据
 * 
 * @author xiaofeng.zhouxf
 * 
 */
@CMbean
public class CacheScaner extends BaseCmScaner<String, Serializable> {
	private static final Logger logger = Logger.getLogger(CacheScaner.class);

	public void scan() {
		CmCacheMuster<String, Serializable> cacheMuster = CmCacheTools
				.getCacheMuster();
		Map<String, CmCache<Serializable>> allCache = cacheMuster.getAllCache();

		for (String key : allCache.keySet()) {
			CmCache<Serializable> cmCache = cacheMuster.getCmCache(key);
			CmCachePolicy cmCachePolicy = cmCache.getCmCachePolicy();
			MonitorData<Serializable> peek = cmCache.peek();
			if (peek == null) {
				if (logger.isInfoEnabled()) {
					logger.info("CacheScaner is runing. Now has no data.");
				}
				break;
			}
			// 利用队列的数据结构特性，从头部开始排查过期数据
			while (DateUtils
					.addSeconds(peek.getDate(), (int) peek.getTimeout()).after(
							new Date())) {
				if (cmCachePolicy.getPolicy() == CachePolicyEnum.STORE_DELETE_CURRENT_DESTORY_FILE
						|| cmCachePolicy.getPolicy() == CachePolicyEnum.STORE_DELETE_LAST_DESTORY_FILE) {
					// 存入文件
					logger.error("Can't save file now. It's not support this time.");
				} else {
					// 默认删除
					MonitorData<Serializable> poll = cmCache.poll();
					if (logger.isInfoEnabled()) {
						logger.info(MessageFormat.format(
								"CloudMonitor data is expried ==>> {0} <<====",
								poll.getValue().toString()));
					}
				}
				peek = cmCache.peek();

				if (peek == null) {
					if (logger.isInfoEnabled()) {
						logger.info("CacheScaner is finished.");
					}
					break;
				}
			}
		}
	}
}
